import service from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginMessageShow } from '@/utils/show-message'
import axios from 'axios'

const getDefaultState = () => {
  return {
    user_info: {},
    resource: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_USERINFO: (state, user_info) => {
    state.user_info = user_info
  },
  SET_RESOURCE: (state, resource) => {
    state.resource = resource
  }
}

const actions = {
  login({ commit, state }, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: process.env.VUE_APP_BASE_API + 'user/login',
        data
      })
        .then((response) => {
          const { data, headers } = response
          const code = data.code
          if (loginMessageShow(code)) {
            // commit('SET_ROLES', data.roles)
            const roles = data.roles
            setToken(headers['x-prac-token'])
            axios({
              method: 'post',
              url: process.env.VUE_APP_BASE_API + 'user/setRole',
              data: {
                user_id: roles[0].user_id,
                role_id: roles[0].role_id
              },
              headers: { 'Authorization': getToken() }
            })
              .then((response) => {
                const { headers } = response
                setToken(headers['x-prac-token'])
                service.getProfile().then(it => {
                  if (it.code === 0) {
                    commit('SET_USERINFO', it.data)
                    service.getResouces({ role: state.user_info.role_name }).then(it => {
                      if (it.code === 0) {
                        commit('SET_RESOURCE', it.data)
                        resolve()
                      } else {
                        reject('获取资源失败')
                      }
                    })
                  }
                })
              })
              .catch((err) => {
                console.log(err)
                reject('选择角色接口出错')
              })
          } else {
            reject('登录信息错误')
          }
        })
        .catch((err) => {
          console.log(err)
          reject('登录接口出错')
        })
    })
  },

  logout({ commit }) {
    return new Promise((resolve, reject) => {
      service.logout().then(it => {
        commit('RESET_STATE')
        removeToken()
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  }

}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
